﻿using System;
using System.Collections.Generic;
using System.IO;
using System.Net;
using System.Text;
using Newtonsoft.Json;
using System.Configuration;

namespace FFSupplier.Common.TKCommon
{
    public class WSHelper
    {
        public static string InvokeService(string webServicePath,Object am,string method)
        {
            string result = "";
            try
            {
                string parajson = JsonConvert.SerializeObject(am);
                byte[] bs = Encoding.UTF8.GetBytes(parajson);
                HttpWebRequest myRequest = (HttpWebRequest)WebRequest.Create(webServicePath);
                myRequest.Method = method;
                myRequest.ContentType = "application/json; charset=utf-8";
                myRequest.ContentLength = bs.Length;
                myRequest.Headers.Add("usercode", ConfigurationManager.AppSettings["MDMAuthUser"]);
                myRequest.Headers.Add("password", ConfigurationManager.AppSettings["MDMAuthPwd"]);

                using (Stream reqStream = myRequest.GetRequestStream())
                {
                    reqStream.Write(bs, 0, bs.Length);
                }
                using (HttpWebResponse myResponse = (HttpWebResponse)myRequest.GetResponse())
                {
                    StreamReader sr = new StreamReader(myResponse.GetResponseStream(), Encoding.UTF8);

                    result = sr.ReadToEnd();
                    sr.Close();
                    myResponse.Close();
                }
            }
            catch (Exception ex)
            {
                result = ex.InnerException.Message.ToString();
            }
            return result;
        }
    }
}
